<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Service\Admin\LoginLogService;
use Common\Repository\AdminRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    //登录页
    public function login()
    {
        return view('admin.login.login');
    }

    //登录操作
    public function doLogin(Request $request)
    {
        $where['where'] = ['name' => $request->username];
        $where['orWhere'] = ['phone' => $request->username];
        $where['field'] = ['id', 'status', 'name'];
        $admin = AdminRepository::getOne($where);
        if ($admin && $admin['status'] != 0) {
            return json_error('该账户已被禁用请联系管理员！');
        }

        //自带验证，里面传验证字段
        $data = ['name' => $request->username, 'password' => $request->password];
        if (Auth::attempt($data)) {
            //登录日志
            $post_data = [
                'ip' => $request->ip(),
                'admin_id' => $admin['id'],
                'admin_name' => $admin['name']
            ];
            LoginLogService::insert($post_data);

            return json_success('登录成功');
        }

        return json_error('用户名或密码错误');
    }

    //退出登录操作
    public function logout()
    {
        //退出登录
        Auth::logout();

        //清除全部session
        Session::flush();

        //重定向
        return redirect()->route('admin.index');
    }
}

